﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using Clipping.Infrastructure.Models;
namespace ClippingMaster
{
    class KeywordsCategorySettingViewModel : GalaSoft.MvvmLight.ViewModelBase
    {
        public event Action OnSaved;
        public event Action OnCanceled;

        private OpMode mode;


        public KeywordsCategorySettingViewModel(Guid parentId)
        {
            this.Category = new KeywordCategory() { Id =Guid.NewGuid (), ParentId =parentId };
            this.mode = OpMode.Add;
            initCommands();
        }
        public KeywordsCategorySettingViewModel(KeywordCategory category)
        {
            this.Category = category;
            this.mode = OpMode.Modify;
            initCommands();
        }

        private void initCommands()
        {

            this.SaveCommand = new GalaSoft.MvvmLight.Command.RelayCommand(save, canSave);
            this.CancelCommand = new GalaSoft.MvvmLight.Command.RelayCommand(cancel);

        }

        private void save()
        {
            this.Category.Name = this.Name;

            KeywordsRepository rep = new KeywordsRepository();

            if (this.mode == OpMode.Add)
            {
                rep.AddCategory(this.Category);
            }
            else
            {
                rep.UpdateCategory(this.Category);
            }
            var handler = this.OnSaved;
            if (handler != null)
                handler();
        }

        private bool canSave()
        {
            if (string.IsNullOrEmpty(Name))
                return false;
            else
                return true;
        }

        private void cancel()
        {
            var handler = this.OnCanceled;
            if (handler != null)
                handler();
        }


        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (_name == value)
                    return;
                _name = value;
                RaisePropertyChanged(() => this.Name);
                (SaveCommand as GalaSoft.MvvmLight.Command.RelayCommand).RaiseCanExecuteChanged();
            }
        }

        public KeywordCategory Category { get; private set; }


        public ICommand SaveCommand { get; set; }
        public ICommand CancelCommand { get; set; }

        enum OpMode
        {
            Add,
            Modify
        }
    }
}
